<?php

namespace app\queue\haikang;

use app\common\model\haikang\HkConsumerMsgWeek;
use app\common\model\QueueErrorLog;
use app\common\model\work_area\WorkAreaStandVoice;
use app\common\service\broadcast\IpBroadcastService;
use think\queue\Job;

class ConsumerMessagesQueue
{
    /**
     * fire方法是消息队列默认调用的方法
     * @param Job $job 当前的任务对象
     * @param array|mixed $data 发布任务时自定义的数据
     */
    public function fire(Job $job, $data)
    {
        $isJobDone = $this->doJob($data);
        if ($isJobDone) {
            // 如果任务执行成功， 记得删除任务
            $job->delete();
        } else {
            /** 如果大于2次则删除该任务 */
            if ($job->attempts() > 2) {
                $job->delete();
            } else {
                $job->release(2); //$delay为延迟时间，表示该任务延迟2秒后再执行
            }
        }
    }

    /**
     * 处理队列消息
     */
    private function doJob($data)
    {
        $hk_consumer_msg_week = HkConsumerMsgWeek::where('create_time', '>=', time() - 5)
            ->where(['device_serial_id' => $data['id']])
            ->where("msg_name", '<>', '雷达侦测')
            ->value('msg_name');
        if (!empty($hk_consumer_msg_week)) {
            $where = ['event_type' => $hk_consumer_msg_week];
        } else {
            $where = ['event_type' => '雷达侦测'];
        }
        //播放广播
        $voice_file = WorkAreaStandVoice::where(['hk_device_serial_id' => $data['id']])
            ->where($where)
            ->order("id DESC")
            ->cache(60)
            ->value('file');
        //40秒以内不报警
        if (empty($hk_consumer_msg_week)) {
            //语音文件服务器域名
            $play_url = 'http://ai.admin.lgsid.com/' . $voice_file;
            //远程调用ip广播
            IpBroadcastService::speech([
                'url' => $play_url,
                'hk_device_serial_id' => $data['id']
            ]);
        }
        //file_put_contents('return.txt', print_r($data, true));
        return true;
    }


    /**
     * 队列失败记录
     * @param $data
     * @param $remarks
     * @return void
     */
    private function fail($data, $remarks = '')
    {
        QueueErrorLog::create([
            'queue_name' => 'ConsumerMessagesQueue',
            'queue_data' => json_encode($data),
            'remarks' => $remarks
        ]);
    }

}